package com.longrise.android.byjk.plugins.dealsituation.course.video2.education.webpicedu;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoConsts;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoParams;
import com.longrise.android.byjk.widget.view.BaseFrameView;
import com.longrise.common.utils.AppUtil;

/**
 * Created by godliness on 2017/7/31.
 * 学历教育
 * 图片+web
 * 课件学习方式
 */

public class WebEduActivity extends BaseActivity<WebEduPresenter> implements WebEduView, BaseFrameView.ReloadListener {

    private static final String TAG = "WebEduActivity";

    private Toolbar mToolbar;

    private WebView mWebView;
    private WebSettings mWebSettings;
    private ImageView mIv;
    private BaseFrameView mBaseFrameView;

    private VideoParams mParams;

    private boolean mWebLoadError;

    @Override
    public int getContentViewId(@Nullable Bundle state) {
        if (state != null) {
            onResInstance(state);
        } else {
            getExtraData();
        }
        return R.layout.activity_webedu;
    }

    private void preformLoad() {
        mPresenter.reLoad();
    }

    /**
     * 加载web资源
     */
    public void loadWebResource(String url) {
        if (isFinishing()) {
            return;
        }
        if(mWebView != null){
            mWebView.loadUrl(url);
        }
    }

    /**
     * 记载图片资源
     */
    public void loadPicResource(String url) {
        if(isFinishing()){
            return;
        }
        if(mIv != null || !strIsEmpty(url)){
            Glide.with(this).load(url).placeholder(R.drawable.bg_error_4).into(mIv);
        }
    }

    private boolean strIsEmpty(String url){
        return TextUtils.isEmpty(url);
    }

    @Override
    public void initView() {
        initTitle();
        mWebView = (WebView) findViewById(R.id.wv_webedu);
        mIv = (ImageView) findViewById(R.id.iv_webedu);
        autoSize(mIv);
        mBaseFrameView = (BaseFrameView) findViewById(R.id.bfv_webedu);
        mBaseFrameView.setOnReloadListener(this);
        initWebSetting();

        preformLoad();
    }

    private void autoSize(ImageView iv){
        int windowWidth = AppUtil.getScreenWidth();
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) iv.getLayoutParams();
        int ivHeight = windowWidth / 2;
        lp.height = ivHeight;
        iv.requestLayout();
    }

    private void initTitle() {
        mToolbar = (Toolbar) findViewById(R.id.byjk_toolbar);
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);

        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initWebSetting() {
        mWebSettings = mWebView.getSettings();
        mWebSettings.setLoadWithOverviewMode(true);
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setJavaScriptEnabled(true);
        //设置 缓存模式 不用缓存 使用localStorage
        mWebSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebSettings.setDomStorageEnabled(true);
        mWebSettings.setAppCacheMaxSize(1024 * 1024 * 8);
        String absolutePath = getApplicationContext().getCacheDir().getAbsolutePath();
        mWebSettings.setAppCachePath(absolutePath);
        mWebSettings.setAllowFileAccess(true);
        mWebSettings.setAppCacheEnabled(true);
        mWebSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        mWebView.setWebChromeClient(mWebChromeClient);
        mWebView.setWebViewClient(mWebViewClient);
    }

    private void getExtraData() {
        Intent extra = getIntent();
        mParams = extra.getParcelableExtra(VideoConsts.VIDEO_PARAMS_PARCELABLE);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable(VideoConsts.VIDEO_PARAMS_PARCELABLE, mParams);
    }

    private void onResInstance(Bundle state) {
        mParams = state.getParcelable(VideoConsts.VIDEO_PARAMS_PARCELABLE);
    }

    @Override
    public void showLoadingDialog() {
        mBaseFrameView.post(new Runnable() {
            @Override
            public void run() {
                loadStartStatus();
            }
        });
    }

    @Override
    public void dismissLoadingDialog() {
        mBaseFrameView.post(new Runnable() {
            @Override
            public void run() {
                loadFinishStatus();
            }
        });
    }

    @Override
    public void showToast(String msg) {
        super.showToast(msg);
    }

    @Override
    public void error() {
        mBaseFrameView.post(new Runnable() {
            @Override
            public void run() {
                loadErrorStatus();
            }
        });
    }

    private void loadStartStatus() {
        mBaseFrameView.setLoadingStatus(BaseFrameView.LoadingStatus.LOADING);
        mBaseFrameView.setVisibility(View.VISIBLE);
    }

    private void loadFinishStatus() {
        mBaseFrameView.setLoadingStatus(BaseFrameView.LoadingStatus.SUCCESS);
        mBaseFrameView.setVisibility(View.GONE);
    }

    private void loadErrorStatus() {
        mBaseFrameView.setLoadingStatus(BaseFrameView.LoadingStatus.ERROR);
        mBaseFrameView.setVisibility(View.VISIBLE);
    }

    @Override
    public void loadPic(String picUrl) {
        loadPicResource(picUrl);
    }

    public void loadWeb(String url) {
        loadWebResource(url);
    }

    @Override
    public void setTitle() {
        if (mParams != null) {
            mToolbar.setTitle(mParams.mCwidName);
        }
    }

    @Override
    public VideoParams getVideoParams() {
        return mParams;
    }

    /**
     * activity是否finish, 接口回调时拦截
     */
    @Override
    public boolean actFinished() {
        return isFinishing();
    }

    @Override
    public void onBack() {
        finish();
    }

    private WebChromeClient mWebChromeClient = new WebChromeClient() {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
        }
    };

    private WebViewClient mWebViewClient = new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (mWebLoadError) {
                error();
            } else {
                mWebLoadError = false;
                dismissLoadingDialog();
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            mWebLoadError = true;
        }
    };

    private void release() {
        detachWebView();
        mPresenter.mHandler.removeCallbacksAndMessages(null);
    }

    private void detachWebView() {
        if (mWebView != null) {
            ViewParent viewParent = mWebView.getParent();
            if (viewParent != null) {
                ((ViewGroup) viewParent).removeView(mWebView);
            }
            mWebView.removeAllViews();
            mWebView.destroy();
            mWebSettings.setJavaScriptEnabled(false);
        }
    }

    @Override
    public void onReload(View v) {
        if (mWebLoadError) {
            loadStartStatus();
            mWebView.reload();
            return;
        }
        mPresenter.reLoad();
    }

    private void sendMessage(){
        mPresenter.toRefrushCourseDetail();
    }

    @Override
    public void onDestroy() {
        release();
        sendMessage();
        super.onDestroy();
    }
}
